package oa.controller;


import java.io.UnsupportedEncodingException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import oa.bean.Goods;
import oa.bean.Gw;
import oa.bean.QXCD;
import oa.bean.QXJS;
import oa.bean.TDep;
import oa.bean.TSystem;
import oa.bean.TUser;
import oa.service.UserService;
import oa.service.impl.GoodsServiceImpl;
import oa.service.impl.GwServiceImpl;
import oa.util.RedisUtil;
import oa.util.StringUtil;

@Controller
@RequestMapping("/xadmin")
public class AdminController {
	@Resource
	private UserService userService;
	@Resource
	private RedisUtil redisUtil;
	@Resource
	private GoodsServiceImpl goodsServiceImpl;
	@Resource
	private GwServiceImpl gwServiceImpl;

	@RequestMapping("/adminindex")
	public String adminindex() {
		return "/xadmin/adminindex";
	}

	@RequestMapping("/adminlogout")
	public String adminloginout(HttpSession session) {
		session.invalidate();
		SecurityUtils.getSubject().logout();
		return "redirect:/adminlogin";
	}

	@RequestMapping("/listmenu")
	@ResponseBody
	public String listmenu(HttpSession session, Model model) {
		// TUser user = (TUser)session.getAttribute("user");
		// TUser user = (TUser)SecurityUtils.getSubject().getPrincipal();
		String username = SecurityUtils.getSubject().getPrincipal().toString();
		TUser user = userService.login(username);
		model.addAttribute("user", user);
		String jsdm = user.getOskey();
		String jsonString = "";
		String menuKey = jsdm + "-menu";
		if (redisUtil.exists(menuKey)) {
			jsonString = (String) redisUtil.get(menuKey);
		} else {
			Map<String, List<QXCD>> json = new HashMap<String, List<QXCD>>();
			json.put("onemenu", userService.listmenu1(jsdm));
			json.put("twomenu", userService.listmenu2(jsdm));
			jsonString = JSON.toJSONString(json);
			redisUtil.set(menuKey, jsonString);
			redisUtil.expired(menuKey, 60);
		}
		return jsonString;
	}

	@RequestMapping("/system/updatesystem")
	@ResponseBody
	public String updatesystem(TSystem sys) {
		if (userService.updatesystem(sys) > 0) {
			return "更新成功";
		} else {
			return "更新出错";
		}
	}

	
	@RequestMapping("/system/qxmanage")
	public String qxmanage() {
		return "/xadmin/system/qxManage";
	}

	@RequiresPermissions("system/qxmanage")
	@RequestMapping("/system/qxmanage-listrole")
	@ResponseBody
	public String qxmanagelistrole() {
		List<QXJS> roles = userService.listrole();
		return JSON.toJSONString(roles);
	}

	@RequestMapping("/system/qxmanage-listjsfortree")
	@ResponseBody
	public String qxmanagelistjsfortree(String jsdm, String flag, HttpSession session) {
		return userService.listjsfortree(jsdm, flag);
	}


	@RequestMapping("/system/qxmanage-listjsforcombox")
	@ResponseBody
	public String qxmanagelistjsforcombox(String jsdm, String flag, HttpSession session) {
		return userService.listjsfortree(jsdm, flag);
	}

	@RequestMapping("/system/qxmanage-rolewindow")
	public String qxmanagerolewindow(String jsdm, Model model) {
		if (!StringUtil.nullOrBlank(jsdm)) {
			model.addAttribute("obj", userService.getrole(jsdm));
		}
		return "/xadmin/system/roleWindow";
	}

	@RequestMapping("/system/qxmanage-delrole")
	@ResponseBody
	public String qxmanagedelrole(String jsdm) {
		if (!StringUtil.nullOrBlank(jsdm)) {
			if (userService.delrole(jsdm) > 0) {
				return "删除成功";
			} else {
				return "删除出错";
			}
		} else {
			return "角色代码不能为空";
		}
	}

	@RequestMapping("/system/qxmanage-addrole")
	@ResponseBody
	public String qxmanageaddrole(QXJS qxjs) {
		if (userService.addrole(qxjs) > 0) {
			return "添加成功";
		} else {
			return "添加出错";
		}
	}

	@RequestMapping("/system/qxmanage-updaterole")
	@ResponseBody
	public String qxmanageupdaterole(QXJS qxjs) {
		if (userService.updaterole(qxjs) > 0) {
			return "修改成功";
		} else {
			return "修改出错";
		}
	}

	@RequestMapping("/system/qxmanage-updaterolezt")
	@ResponseBody
	public String qxmanageupdaterolezt(String jsdm, int zt) {
		if (userService.updaterolezt(jsdm, zt) > 0) {
			return "修改成功";
		} else {
			return "修改出错";
		}
	}

	@RequestMapping("/system/qxmanage-setrolewindow")
	public String qxmanagesetrolewindow(String jsdm, Model model) {
		model.addAttribute("jsdm", jsdm);
		return "/xadmin/system/setRoleWindow";
	}

	@RequestMapping("/system/qxmanage-setrole")
	@ResponseBody
	@Transactional
	public String qxmanagesetrole(String jsdm, String jscd) throws Exception {
		String[] jscds = jscd.split(",");
		if (userService.updaterolecd(jsdm, jscds) > 0) {
			return "修改成功";
		} else {
			return "修改出错";
		}
	}

	@RequestMapping("/system/usermanage")
	public String usermanage() {
		return "/xadmin/system/userManage";
	}

	@RequiresRoles("admin")
	@RequestMapping("/system/usermanage-listuser")
	@ResponseBody
	public String usermanagelistuser(String username, String fullname, String oskey, Integer deptid) {
		List<TUser> users = userService.listuser(username, fullname, oskey, deptid);
		return JSON.toJSONString(users);
	}

	@RequestMapping("/system/usermanage-userwindow")
	public String usermanageuserwindow(Integer userid, Model model) {
		if (userid != null) {
			TUser user = userService.getuser(userid);
			model.addAttribute("obj", user);
		}
		model.addAttribute("userid", userid);
		return "/xadmin/system/userWindow";
	}

	@RequestMapping("/system/usermanage-deluser")
	@ResponseBody
	public String usermanagedeluser(Integer userid) {
		if (!StringUtil.nullOrBlank(userid)) {
			if (userService.deluser(userid) > 0) {
				return "删除成功";
			} else {
				return "删除出错";
			}
		} else {
			return "用户代码不能为空";
		}
	}

	@RequestMapping("/system/usermanage-adduser")
	@ResponseBody
	public String usermanageadduser(TUser user) {
		if (userService.adduser(user) > 0) {
			return "添加成功";
		} else {
			return "添加出错";
		}
	}

	@RequestMapping("/system/usermanage-updateuser")
	@ResponseBody
	public String usermanageupdateuser(TUser user) {
		if (userService.updateuser(user) > 0) {
			return "修改成功";
		} else {
			return "修改出错";
		}
	}

	@RequestMapping("/system/usermanage-updateuserzt")
	@ResponseBody
	public String usermanageupdateuserzt(Integer userid, Integer zt) {
		if (userService.updateuserzt(userid, zt) > 0) {
			return "修改成功";
		} else {
			return "修改出错";
		}
	}

	@RequestMapping("/system/usereditinfo")
	public String usereditinfo(Map<String, Object> model) {
		String username = (String) SecurityUtils.getSubject().getPrincipal();
		TUser user = userService.login(username);
		model.put("obj", user);
		return "/xadmin/system/userEditInfo";
	}

	@RequestMapping("/system/publicinfo")
	public String publicinfo() {
		return "/xadmin/system/publicInfo";
	}

	@RequestMapping("/system/deptmanage")
	public String deptmanage() {
		return "/xadmin/system/DeptManage";
	}

	@RequiresRoles("admin")
	@RequestMapping("/system/deptmanage-listdept")
	@ResponseBody
	public String deptmanagelistdept() {
		List<TDep> depts = userService.listdept();
		StringBuffer s = new StringBuffer();
		s.append("{\"rows\":").append(JSON.toJSONString(depts).replaceAll("fid", "_parentId"));
		s.append(",\"total\":").append(depts.size()).append("}");
		return s.toString();
		// return JSON.toJSONString(depts);
	}

	@RequestMapping("/system/deptmanage-deptwindow")
	public String deptmanagedeptwindow(Integer id, Model model) {
		if (id != null) {
			TDep dept = userService.getdept(id);
			model.addAttribute("obj", dept);
		}
		model.addAttribute("id", id);
		return "/xadmin/system/deptWindow";
	}

	@RequestMapping("/system/deptmanage-deldept")
	@ResponseBody
	public String deptmanagedeldept(Integer id) {
		if (!StringUtil.nullOrBlank(id)) {
			if (userService.deldept(id) > 0) {
				return "删除成功";
			} else {
				return "删除出错";
			}
		} else {
			return "用户代码不能为空";
		}
	}

	@RequestMapping("/system/deptmanage-adddept")
	@ResponseBody
	public String deptmanageadddept(TDep dept) {
		if (userService.adddept(dept) > 0) {
			return "添加成功";
		} else {
			return "添加出错";
		}
	}

	@RequestMapping("/system/deptmanage-updatedept")
	@ResponseBody
	public String deptmanageupdatedept(TDep dept) {
		if (userService.updatedept(dept) > 0) {
			return "修改成功";
		} else {
			return "修改出错";
		}
	}

	@RequestMapping("/system/deptmanage-updatedeptzt")
	@ResponseBody
	public String deptmanageupdatedeptzt(Integer id, Integer zt) {
		if (userService.updatedeptzt(id, zt) > 0) {
			return "修改成功";
		} else {
			return "修改出错";
		}
	}

	@RequestMapping("/system/deptmanage-listdeptfortree")
	@ResponseBody
	public String deptmanagelistdeptfortree() {
		return userService.listdeptfortree();
	}

	/********************************************************************************************/

	/**
	 * 查询商品列表
	 * 
	 * @return
	 */
	@RequestMapping("system/goodsList")
	public String list(HttpServletRequest request) {
		List<Goods> listgoods = goodsServiceImpl.getAll();
		System.out.println(listgoods);
		request.getSession().setAttribute("listgoods", listgoods);
		return "/xadmin/system/goodsList";
	}

	/**
	 * 点击商品修改——————>[跳转]到商品修改页面[通过获取商品id来获取要修改的商品信息]
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("system/updateGoods")
	public String updateGoods(HttpServletRequest request) {
		String id = request.getParameter("id");
		Goods goods = new Goods();
		goods.setId(id);
		List<Goods> listgoods = goodsServiceImpl.getGoodById(goods);
		request.getSession().setAttribute("adminGood", listgoods.get(0));
		return "/xadmin/system/updateGoods";
	}

	/**
	 * 修改商品
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("system/update")
	public String update(HttpServletRequest request) throws UnsupportedEncodingException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		String price = request.getParameter("price");
		String stock = request.getParameter("stock");
		String img1 = request.getParameter("img1");
		String img2 = request.getParameter("img2");
		String img3 = request.getParameter("img3");
		String img4 = request.getParameter("img4");
		String gstatus = request.getParameter("gstatus");
		Goods goods = new Goods();
		goods.setId(id);
		goods.setName(name);
		goods.setPrice(Double.parseDouble(price));
		goods.setStock(Integer.parseInt(stock));
		goods.setImg1(img1);
		goods.setImg2(img2);
		goods.setImg3(img3);
		goods.setImg4(img4);
		goods.setGstatus(Integer.parseInt(gstatus));

		int result = goodsServiceImpl.update(goods);
		if (result == 1) {
			request.setAttribute("success", "修改信息成功！");
			return "redirect:/xadmin/system/goodsList";
		} else {
			request.setAttribute("error", "修改信息失败！");
			return "redirect:/xadmin/system/goodsList";
		}
	}
	
	
	/**
	 * 跳转新增商品页面
	 * @param request
	 * @return
	 */
	@RequestMapping("system/insertGoods")
	public String insertGoods(HttpServletRequest request){	
		
		System.out.println("adskljfajsdlkfj");
		return "xadmin/system/insertGoods";	
	}
	/**
	 * 统一新增商品的方法
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("system/insert")
	public String insert(HttpServletRequest request)throws UnsupportedEncodingException {
		String name = request.getParameter("name");
		String price = request.getParameter("price");
		String stock = request.getParameter("stock");
		String img1 = request.getParameter("img1");
		String img2 = request.getParameter("img2");
		String img3 = request.getParameter("img3");
		String img4 = request.getParameter("img4");
		Goods goods = new Goods();
		goods.setName(name);
		goods.setPrice(Double.parseDouble(price));
		goods.setStock(Integer.parseInt(stock));
		goods.setImg1(img1);
		goods.setImg2(img2);
		goods.setImg3(img3);
		goods.setImg4(img4);
		int result  = goodsServiceImpl.insert(goods);
		if(result == 1) {
			System.out.println("增加成功");
			return "redirect:/xadmin/system/goodsList";
			
		}else {
			System.out.println("增加失败");
			return "/xadmin/system/insertGoods";
		}
	
	}

		
	/**
	 * 根据id删除
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("system/del")
	public String del(HttpServletRequest request) throws UnsupportedEncodingException {

		String id = request.getParameter("id");
		Goods goods = new Goods();
		goods.setId(id);
		int result = goodsServiceImpl.delete(goods);
		if (result == 1) {
			request.setAttribute("success", "删除成功！");
			return "redirect:/xadmin/system/goodsList";
		} else {
			request.setAttribute("error", "删除失败！");
			return "/xadmin/system/goodsList";
		}
	}
	
	

	/**
	 * 商品搜索
	 * 
	 * @return
	 */
	@RequestMapping("system/fuzzy")
	public String fuzzy(HttpServletRequest request) {
		String goods = request.getParameter("goods");
		List<Goods> listgoods = goodsServiceImpl.getGoodByName("%" + goods + "%");
		request.getSession().setAttribute("listgoods", listgoods);
		return "/xadmin/system/goodsList";
	}
	/**
	 * 更新商品状态
	 * @param request
	 * @return
	 */
	@RequestMapping("system/updatezt")
	public String zt(HttpServletRequest request) {
		String id = request.getParameter("id");
		Goods goods = new Goods();
		goods.setId(id);
		String gstatus = request.getParameter("gstatus");	
		int zt = goodsServiceImpl.updatezt(id,gstatus);		
		if(zt>0) {
			request.getSession().setAttribute("goods", zt);
			System.out.println("更新成功！");
			return "redirect:/xadmin/system/goodsList";
		}else {
			System.out.println("更新失败！");
			return "redirect:/xadmin/system/goodsList";
		}
		
	}
	


/*******************************订单管理*****************************************/	
/**
 * 查询订单
 * @param request
 * @return
 */
@RequestMapping("system/dingdan")
public String dingdan(HttpServletRequest request) {
	Gw gw = new Gw();
	List<Gw> gwgoods = gwServiceImpl.getAll(gw);
	System.out.println(gwgoods);
	request.getSession().setAttribute("gwgoods", gwgoods);
	return "/xadmin/system/dingdan";
}
	
/**
 * 更新订单状态
 * @param request
 * @return
 */
@RequestMapping("system/updatedd")
public String updatedd(HttpServletRequest request) {
	String id = request.getParameter("id");
	Gw gw = new Gw();
	gw.getGid();
	String zt = request.getParameter("zt");	
	int ddzt = gwServiceImpl.updateddzt(id,zt);		
	if(ddzt>0) {
		request.getSession().setAttribute("goods", zt);
		System.out.println("更新成功！");
		return "redirect:/xadmin/system/dingdan";
	}else {
		System.out.println("更新失败！");
		return "redirect:/xadmin/system/dingdan";
	}
	
}
	
	

}